package com.webserver.http;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class HttpServletRequest {
    private Socket socket;
   // public  String line;
   private Map<String,String> headers=new HashMap<>();
   private String method;//请求方式
   private String uri;//抽象路径
   private String protocol;//协议
    public  HttpServletRequest(Socket socket) throws IOException {
        this.socket=socket;

        parseContent();
        parseHeaders();
        parseRequestLine();
    }
    /*
    * 解析请求行
    * */
    private  void  parseRequestLine() throws IOException {
        String line = readLine();
        System.out.println(line);

        //请求行的相关信息
        //将请求行内容拆分出来并分别赋值给三个变量
        String[] data = line.split("\\s");
        method = data[0];
        uri = data[1];
        protocol = data[2];

        //测试路径:http://localhost:8088/myweb/index.html
        System.out.println("method:"+method);//method:GET
        System.out.println("uri:"+uri);//uri:/myweb/index.html
        System.out.println("protocol:"+protocol);//protocol:HTTP/1.1

    }
    /*
     * 解析消息头
     * */
    private  void  parseHeaders() throws IOException {

        while (true) {
          String  line = readLine();
            if (line.isEmpty()){
                break;
            }
            System.out.println("消息头："+line);
           String[] data =line.split(":\\s");
            headers.put(data[0],data[1]);
        }
        System.out.println("headers:"+headers);
    }
    /*
     * 解析消息正文
     * */
    private  void  parseContent(){

    }
    private  String readLine() throws IOException {
        InputStream in = socket.getInputStream();
        StringBuilder builder = new StringBuilder();
        int d;
        char pre='a',cur='a';//pre上一次读取的字符  cur本次读取到的字符
        while((d = in.read())!=-1){
            cur = (char)d;//将本地读取的字节转换为字符赋值给cur
            if(pre==13&cur==10){//是否连续读取到了回车+换行
                break;
            }
            builder.append(cur);//将本次读取的字符拼接到StringBuilder中
            pre = cur;//在进行下一个字符读取前将本地读取的字符记录为上次读取的字符
        }
        return builder.toString().trim();
    }

    public String getMethod() {
        return method;
    }

    public String getUri() {
        return uri;
    }

    public String getProtocol() {
        return protocol;
    }
    }
